import React from "react";
import {Layout, Menu,Tabs,Button,Row,Col } from 'antd';
import {withRouter} from 'react-router-dom'
import SetMenu from '../../components/AccountSetting/SetMenu'
import {action, manage} from "../../store/action";
import store from "../../store/store";
import {LinkOutlined,FileTextOutlined,FolderOutlined,MenuUnfoldOutlined, MenuFoldOutlined,     } from '@ant-design/icons';
import $ from 'jquery'
import API from '../../api/api'
import './Index.css'
import BreadCrumb from "../../components/BreadCrumb/BreadCrumb";
import judgePath from '../../service/judgePath'
var preheight;
const {SubMenu} = Menu;
const {Header, Content, Sider} = Layout;
const { TabPane } = Tabs;
// 过滤的侧边栏功能集合，默认是首页的链接
let routes =  API.getLinks("link","side");
// lock 是为了实现getSubElement(module.moduleId)函数的递归，通过lock来防止内存穿透
let lock  = true;
// 该变量是在首页模块下为 "link",在文件存放模块中为 "module" ,在后台管理模块中为 "manage",因为三类模块都调用了一个函数 sider()，所以通过该变量来选择函数中相符合的代码执行
let isLink = "link";
let getModule = [];
let getAdminModule = [];
let getManageModule = [];
let module_url = require('../../util/config').url.module_url;
let manageModule_url = require('../../util/config').url.moduleManage_url;
let common_url;
let routeInfo

let rootSubmenuKeys = [];

class Index extends React.Component {
    constructor(props) {
        super(props);
        const w=document.documentElement.clientWidth;
        let tmpHeight ;
        let tmpSiderWidth;
        if(w>1370){
            tmpHeight = "4rem"
            tmpSiderWidth = "16rem"
        }else {
            tmpHeight = "3rem"
            tmpSiderWidth = "12rem"
        }

        this.state={
            siderWidth:tmpSiderWidth,
            navigation_bar:tmpHeight,
            openKeys:[],
            menuDisplay:"inline-block",
            width:"1.3rem",
            collapsed: false,
            mod:'top',
            //collapsed_status: true表示开，false表示关
            collapsed_status:true,
            menu:[
                {
                    menuId: null,
                    menuList: null,
                    menuLength: null
                }
            ],
            lock:null
        }

        this.sider = this.sider.bind(this);
        this.bindStore = this.bindStore.bind(this)
        store.subscribe(this.bindStore)
        console.log("page frame index constructor props",this.props)
        routeInfo = this.props.location.pathname
        this.getSubMenuKeys();
    }

    UNSAFE_componentWillReceiveProps(nextProps, nextContext) {
        this.getSubMenuKeys();
        console.log("page frame index UNSAFE_componentWillReceiveProps nextProps",nextProps)
        routeInfo = nextProps.location.pathname
    }

    getHeadTabModule=(modules)=>{

        let headTabModule = modules.find(item=>item.moduleParentId==0)

        this.getModuleSubmenuKeys(modules,headTabModule);

    }

    getModuleSubmenuKeys=(modules,headTabModule)=>{
        if(headTabModule!=undefined){
            for(let i=0;i<headTabModule.length;i++){
                let subModule = modules.find(item=>item.moduleParentId==headTabModule[i])
                this.getModuleSubmenuKeys(modules,subModule);
            }
        }
    }

    getSubMenuKeys =_=>{
        rootSubmenuKeys = [];
        let getModule = JSON.parse(sessionStorage.getItem("getModule"));
        let getAdminModule = JSON.parse(sessionStorage.getItem("getAdminModule"));
        let getManageModule = JSON.parse(sessionStorage.getItem("getManageModule"));
        this.getHeadTabModule(getModule);
        getModule.map(item=>{
            if(item.moduleType=="folder-d"){
                rootSubmenuKeys.push({
                        moduleParentId:item.moduleParentId,
                        moduleId:item.moduleId
                    })
            }
        });
        getAdminModule.map(item=>{
            if(item.moduleType=="folder-d"){
                rootSubmenuKeys.push({
                    moduleParentId:item.moduleParentId,
                    moduleId:item.moduleId
                })
            }
        });
        // getManageModule.map(item=>{
        //     if(item.moduleType=="folder-d"){
        //         rootSubmenuKeys.push({
        //             moduleParentId:item.moduleParentId,
        //             moduleId:item.moduleId
        //         })
        //     }
        // });
        console.log(rootSubmenuKeys)
    }


    handleModeChange = e => {
        const mode = e.target.value;
        this.setState({ mode });
    };

    bindStore(){
        // if(store.getState().url != window.location.href){
        //         //     if(window.location.href.indexOf("/eip/module-manage/") != -1){
        //         //         alert(store.getState().url)
        //         //     }
        //         //     //会监听redux的pushUrl方法
        //         //     else
        //         //         this.props.history.push(store.getState().url);
        //         // }
        this.setState({})
    }

    sider() {
        let sa = [];
        //渲染首頁鏈接功能
        if(isLink == "link"){
            sa= routes.map(route => {
                return (
                    <Menu.Item icon={<LinkOutlined />} key={route.key}>
                        {/*<a href={route.link} target="_blank">{route.name}</a>*/}
                        <span dangerouslySetInnerHTML={{__html:route.link }}></span>
                    </Menu.Item>
                )
            })
        }
        //渲染模塊獲取功能
        else if(isLink == "module"){
            sa = routes.map(route => {
                if(route.moduleType=="folder-d"){
                    let key = route.moduleId;
                    let folder = this.getSubModuleElement(key,route.moduleName)
                    console.log("folder:", folder)
                    return folder;
                }
            });
        }
        //后台管理模塊
        else{
            sa = routes.map(route => {
                if(route.moduleType == "file-d" || route.moduleType == "article-d" ){
                    return <Menu.Item key={route.moduleId} onClick={_=>{this.props.history.push(route.moduleUrl)}}>{route.moduleName}</Menu.Item>
                }
                else {
                    return (
                        getManageModule.length==0
                            ?
                            <Menu.Item key={route.moduleId}
                                       onClick={_=>{
                                           // action("folder&0")
                                           this.props.history.push(common_url + "folder&0")}}
                            >
                                {route.moduleName}
                            </Menu.Item>
                            :
                            <SubMenu style={{title:route.moduleName}} key={route.moduleId} title={route.moduleName} onTitleClick={_=>{
                                // action("folder&0")
                                this.props.history.push(common_url + "folder&0")}}
                            >
                                {this.getRootManageModule()}
                            </SubMenu>
                    )
                }
            })
        }
        return sa;
    }

    getRootManageModule() {
        let subObjs = []
        let items = getManageModule.filter(item => item.moduleParentId == "0" && item.moduleType=="folder-d")
        subObjs = this.recursiveManageElement(items);
        return subObjs;
    }

    // recursive(submenu){
    //     {
    //         let tmp = getModule.filter(module => module.moduleParentId == submenu.key)
    //         console.log("tmp:",tmp)
    //         for(let i = 0;i<this.state.menu.length;i++){
    //             let ele = this.state.menu[i];
    //             if(ele.menuId == submenu.key){
    //                 this.setState({});
    //                 console.log("已经添加")
    //                 return
    //             }
    //         }
    //         console.log("添加一个")
    //         let menuList = this.state.menu.concat({
    //             menuId: submenu.key,
    //             menuList: tmp,
    //             menuLength: tmp.length
    //         });
    //         menu(menuList)
    //         //state未及时更新：因为react中的使用了基于事务（传送门，关于事务原理的解析）的异步更新机制，但对于这个异步的理解，又跟ajax的异步有所不同，因为毕竟react是一个js框架，所有的操作都是单线程
    //     }
    //     console.log("recursive 已结束",this.state)
    // }

    //manageModule
    getSubManageElement(key,title){
        if(typeof key == "number"){
            let items = getManageModule.filter(item => item.moduleParentId == key && item.moduleType=="folder-d")
            if(items.length==0){
                return (
                    <Menu.Item
                        key= {"manage_"+key}
                        onClick={
                            submenu => {
                                let e = "folder&" + key;
                                // action(e);
                                submenu.key = key;
                                // this.recursive(submenu);
                                this.props.history.push(common_url+e)
                            }
                        }
                    >
                        {title}
                    </Menu.Item>
                )
            }else {
                return (
                    <SubMenu
                        // icon={<FolderOutlined />}
                        key= {"manage_"+key}
                        title={title}
                        style={{title:title}}
                        onTitleClick={
                            submenu => {
                                let e = "folder&" + key;
                                // action(e);
                                submenu.key = key;
                                // this.recursive(submenu);
                                this.props.history.push(common_url+e)
                            }
                        }>
                        {this.recursiveManageElement(items)}
                    </SubMenu>
                )
            }
        }
    }

    recursiveManageElement(items){
        let subObj = [];
        for(let i = 0;i < items.length;i++){
            let module = items[i];
            subObj.push(this.getSubManageElement(module.moduleId,module.moduleName))
        }
        return subObj;
    }

    //moduleElement
    getSubModuleElement(key,title){
        console.log("getSubElement2(key)",key)
        // 接收对象集合并返还
        let subObj = [];
        // 若传入的key值类型为number ,lock 设置为true
        if(typeof key == "number"){
            let items = getModule.filter(item => item.moduleParentId == key && item.moduleType == "folder-d" )
            if(items.length==0){
                subObj = (
                    <Menu.Item
                        icon={<FolderOutlined />}
                        key={key}
                        onClick={submenu => {
                            console.log("submenu",submenu)
                            let e = "folder&"+submenu.key;
                            // action(e);
                            // this.recursive(submenu);
                            this.props.history.push(common_url+e)}}
                    >
                        {title}
                    </Menu.Item>
                )
            }else{
                subObj = (
                    <SubMenu
                        icon={<FolderOutlined />}
                        key= {key}
                        title={title}
                        onTitleClick={
                        submenu => {
                            console.log("submenu",submenu)
                            let e = "folder&"+submenu.key;
                            // action(e);
                            // this.recursive(submenu);
                            this.props.history.push(common_url+e)}}
                    >
                        {this.recursiveModuleElement(items)}
                    </SubMenu>
                )
            }
        }
        console.log("getSubElement2执行结束。。。")
        return subObj;
    }

    recursiveModuleElement(items){
        let subObj = [];
        for(let i = 0;i < items.length;i++){
            let module = items[i];
            subObj.push(this.getSubModuleElement(module.moduleId,module.moduleName))
        }
        return subObj;
    }

    handleMouseUserOver() {
        preheight = document.getElementById("added-title").style.height;
        document.getElementById("added-title").style.height = '300px'
    }

    handleMouseOut() {
        document.getElementById("added-title").style.height = preheight
    }

    toggleCollapsed = () => {
        this.setState({collapsed_status:!this.state.collapsed_status})
        //监控屏幕宽度
        let screenWidth=$(window).width();
        //content与侧边栏的距离
        let width=null;
        //侧边栏收缩后的宽度
        let menuWidth=null;
        //侧边栏的顶层是否可见
        let menuDisplay=null;
        let collapsed = null;
        // if(this.state.collapsed==true){
        //     width="1.3rem"
        // }else {
        //     width="1.3rem"
        // }
        menuDisplay = "inline-block"
        collapsed = !this.state.collapsed
        this.setState({
            // width:width,
            menuDisplay:menuDisplay,
            // collapsed: !this.state.collapsed,
            collapsed: collapsed,
        });

    };

    handleModeChange = e => {
        const mode = e.target.value;
        this.setState({ mode });
    };

    logout=_=>{
        sessionStorage.clear();
        localStorage.clear();
        this.props.history.push("/login")
    }

    getInitTabSelected=()=>{
        let path = routeInfo;
        //1、首页管理
        if(path=="/eip/index" || path=="/eip/table/notice" || path == "/eip/table/activity" || path.indexOf("/eip/file/notice")>=0 || path.indexOf("/eip/file/activity")>=0){
            isLink="link"
            routes = API.getLinks("link","side")
            sessionStorage.setItem("tab","index")
        }
        //2、用户浏览模块
        if(path.indexOf("/eip/module/")>=0){
            isLink="module"
            let arr = path.split("/");
            let item = arr[3].split("&")
            let type = item[0];
            if(type=="folder"){
                type="folder-d"
            }
            let id = item[1];
            let _breadCrumbList = API.getBreadCrumbs({type,id})
            sessionStorage.setItem("breadCrumbList",JSON.stringify(_breadCrumbList));
            let reverseBreadCrumbList = _breadCrumbList.reverse()
            sessionStorage.setItem("tab",reverseBreadCrumbList[0].ID)
            routes = getModule.filter(route => route.moduleParentId == reverseBreadCrumbList[0].ID)
            common_url = module_url;
        }
        if(path.indexOf("/eip/table/file&")>=0 || path.indexOf("/eip/table/article&")>=0 || path.indexOf("/eip/table/folder&")>=0){
            isLink="module"
            let arr = path.split("/");
            let item = arr[3].split("&")
            let type = item[0];
            if(type=="file"){
                type="file-d"
            }else if(type=="article"){
                type="article-d"
            }
            let id = item[1];
            let _breadCrumbList = API.getBreadCrumbs({type,id})
            sessionStorage.setItem("breadCrumbList",JSON.stringify(_breadCrumbList));
            let reverseBreadCrumbList = _breadCrumbList.reverse()
            sessionStorage.setItem("tab",reverseBreadCrumbList[0].ID)
            routes = getModule.filter(route => route.moduleParentId == reverseBreadCrumbList[0].ID)
            common_url = module_url;
        }
        if(path.indexOf("/eip/file/file/")>=0 || path.indexOf("/eip/file/article/")>=0 ){
            isLink="module"
            let arr = path.split("/");
            let type = arr[3];
            let id = arr[4];
            let _breadCrumbList = API.getBreadCrumbs({type,id})
            sessionStorage.setItem("breadCrumbList",JSON.stringify(_breadCrumbList));
            let reverseBreadCrumbList = _breadCrumbList.reverse()
            sessionStorage.setItem("tab",reverseBreadCrumbList[0].ID)
            routes = getModule.filter(route => route.moduleParentId == reverseBreadCrumbList[0].ID)
            common_url = module_url;
        }
        //3、后台管理
        if(judgePath(path)){
            isLink="manage"
            common_url = manageModule_url;
            routes = JSON.parse(sessionStorage.getItem("getAdminModule")).filter(item => item.moduleParentId != 0)
            sessionStorage.setItem("tab","manage")
        }
    }

    onSelect=item=>{
        console.log("onClick:",item)
    }

    componentDidMount() {
        // $.ajaxSetup({
        //     type: "get",
        //     headers: {'Authorization':localStorage.getItem("item")}
        // });
        window.addEventListener('resize', this.handleResize.bind(this))
    }

    //移除监听器，防止多个组件之间导致this的指向紊乱
    componentWillUnmount() {
        window.removeEventListener('resize', this.handleResize.bind(this))
    }

    ele_content = document.getElementById("content");

    handleResize = e => {
        try {
            //e.target.innerWidth是浏览器窗口的宽度
            // 根据宽度不同进行操作
            if( e.target.innerWidth>1547){
                this.setState({navigation_bar:"4rem"})
                this.setState({siderWidth:"16rem"})
            }else{
                this.setState({navigation_bar:"3rem"})
                this.setState({siderWidth:"12rem"})
            }
        }catch (e) {

        }

    }

    render() {
        const { mode } = this.state;
        const dynamicHeight = document.documentElement.clientHeight-Number.parseInt(getComputedStyle(window.document.documentElement)['font-size'])*Number.parseInt(this.state.navigation_bar)
        console.log("页面高度：",dynamicHeight)
        console.log("页面宽度：",document.documentElement.clientWidth)
        getModule = JSON.parse(sessionStorage.getItem("getModule"));
        getAdminModule = JSON.parse(sessionStorage.getItem("getAdminModule"));
        getManageModule = JSON.parse(sessionStorage.getItem("getManageModule"));
        this.getInitTabSelected();
        console.log("frame index",this.props)
        console.log("openKeys:",this.state.openKeys)
        return (
            <Layout>
                <div style={{backgroundColor:"#001529"}}>
                    <div style={{height:this.state.navigation_bar,lineHeight:this.state.navigation_bar,textAlign:"center"}}>
                        <span >
                            {
                                this.state.collapsed_status ? <img src={"/msi_logo.png"} style={{width:"auto",height:"100%"}} ></img> : null
                            }
                            <Button type="primary" onClick={this.toggleCollapsed} style={{ display:"inline-block",backgroundColor:"#001529",border:"1px #001529 solid",}}>
                                {React.createElement(this.state.collapsed ? MenuUnfoldOutlined : MenuFoldOutlined)}
                            </Button>
                        </span>
                    </div>
                    <Sider
                        className={"sider-menu"}
                        // collapsible
                        collapsed={this.state.collapsed}
                        onCollapse={this.toggleCollapsed}
                        width={this.state.siderWidth}
                        scroll={{ x: 100 }}
                        theme={"dark"}
                        style={{
                            height:dynamicHeight,
                            // height: '92.5vh',
                            // marginBottom:"2rem",
                            // display:this.state.menuDisplay,
                            // left: 0,
                            // zIndex:100,
                            overflow: 'auto',
                            //保证侧边栏和内容区域可以独立滑动
                            // position: 'fixed',
                        }}
                    >
                            <Menu
                                style={{display: "inline-block"}}
                                mode="inline"
                                theme="dark"
                                inlineCollapsed={this.state.collapsed}
                            >
                                { this.sider() }
                            </Menu >
                        {/*</Scrollbars>*/}
                    </Sider>
                </div>
                <Layout style={{backgroundColor:"#fff"}}>
                    <Header style={{height:this.state.navigation_bar,paddingLeft:"0.5rem",boxShadow:"0 1px 4px #00152914"}}>
                        <Row className="header-inner-gride header-inner-gride-row" >
                            <Col className="header-inner-gride" span={17}>
                                <Layout id={"tabLayout"} style={{height:"100%"}}>
                                    <Tabs activeKey={sessionStorage.getItem("tab")} onChange={item => {
                                        if(item=="index"){
                                            console.log(item)
                                            sessionStorage.setItem("coordinate",item)
                                            sessionStorage.setItem("tab",item)
                                            sessionStorage.setItem("href",window.location.href)
                                            routes = API.getLinks("link","side");
                                            isLink = "link";
                                            this.props.history.push("/eip/index")
                                            sessionStorage.setItem("menu_list","/eip/index")
                                        }
                                        else if(item == "manage"){
                                            sessionStorage.setItem("coordinate","null&null")
                                            sessionStorage.setItem("tab",item)
                                            sessionStorage.setItem("href",window.location.href)
                                            sessionStorage.setItem("menu_list","/eip/manage")
                                            // let arr = [];
                                            // arr = JSON.parse(sessionStorage.getItem("getAdminModule")).filter(item => item.moduleUrl == "/eip/manage")
                                            common_url = manageModule_url;
                                            routes = JSON.parse(sessionStorage.getItem("getAdminModule")).filter(item => item.moduleParentId != 0)
                                            // routes = featureRoutes.filter(item => item.parentPath == '/eip/manage');
                                            action("null&null")
                                            manage("/eip/manage");
                                            console.log("routes:",routes)
                                            isLink = "manage";
                                            this.props.history.push("/eip/manage")
                                        }
                                        else {
                                            let e = "folder&"+parseInt(item);
                                            action(e);
                                            sessionStorage.setItem("moduleParentId",item)
                                            sessionStorage.setItem("coordinate",e)
                                            this.props.history.push("/eip/module/"+e)
                                            sessionStorage.setItem("menu_list","/eip/module/"+e)
                                            sessionStorage.setItem("tab",item)
                                            sessionStorage.setItem("href",window.location.href)
                                            isLink = "module";
                                            common_url = module_url;
                                            routes = getModule.filter(route => route.moduleParentId == item)
                                        }

                                    }} tabPosition={mode} style={{display:"inline-block",height:"100%",marginLeft:"1rem",marginRight:"1rem"}}>
                                        <TabPane tab={"首页"} key={"index"}/>
                                        {getModule.map(moduleTitle => {
                                            if(moduleTitle.moduleParentId == 0){
                                                return (
                                                    <TabPane tab={moduleTitle.moduleName} key={moduleTitle.moduleId}/>
                                                )
                                            }
                                        })}
                                        {
                                            sessionStorage.getItem("getAdminModule") && (JSON.parse(sessionStorage.getItem("getAdminModule")).filter(item => item.moduleParentId == 0).length>0) ?
                                                <TabPane tab={"后台管理"} key={"manage"} />:null
                                        }
                                    </Tabs>
                                </Layout>
                            </Col>
                            <Col className="header-inner-gride" span={7} style={{textAlign:"center" ,lineHeight:this.state.navigation_bar}}>
                                <SetMenu logout={this.logout} ></SetMenu>
                            </Col>
                        </Row>
                    </Header>
                    <div className={"breadCrumb"} style={{marginTop:"0.5rem",marginLeft:"1.3rem",background:"white"}}>
                        <BreadCrumb routeInfo={routeInfo}/>
                    </div>
                    <Layout id={"content"} style={{
                        overflow: 'scroll',
                        maxHeight: Number.parseInt(dynamicHeight)-Number.parseInt(50)+"px",
                        overflowX: "hidden",
                        marginLeft:this.state.width,
                        color: "#000C17"}}>
                        <Content className="content"
                        >
                            {this.props.children}
                        </Content>
                    </Layout>
                </Layout>
            </Layout>
        );
    }


}

export default withRouter(Index);

